
/**
 * 歌词数据
 */
const lrcData = parseLrc(lrc);
/**
 * 全局需要的dom
 */
const doms = {
    audio: document.querySelector('audio'),
    container: document.querySelector('.container'),
    lyricUl: document.querySelector('.lyric-ul')
}
/**
 * 解析歌词字符串为数组对象
 * @param {*} lrc 歌词字符串
 * @returns 
 */
function parseLrc(lrc) {
    let lrcArr = [];
    lrc.split('\n').forEach(line => {
        let split = line.split(']');
        let timeStr = split[0].replace('[', '');
        if (timeStr && split[1]) {
            lrcArr.push({
                time: parseTime(timeStr),
                text: split[1]
            })
        }
    });
    return lrcArr;
}

/**
 * 解析事件字符串为数字（秒）
 * @param {*} timeStr 时间字符串
 * @returns 
 */
function parseTime(timeStr) {
    let timeArr = timeStr.split(':');
    return +timeArr[0] * 60 + +timeArr[1];
}

/**
 * 获取当前播放的歌词索引
 * @returns 
 */
function activeIndex() {
    let curTime = doms.audio.currentTime;
    let index = lrcData.findIndex(item => curTime < item.time)
    return index == -1 ? lrcData.length - 1 : index - 1;
}

/**
 * 创建歌词元素
 */
function initLrcEl() {
    var frag = document.createDocumentFragment(); //文档片段
    lrcData.forEach((item, index) => {
        let lrcEl = document.createElement('li');
        lrcEl.textContent = item.text;
        lrcEl.dataset.index = index
        // lrcEl.addEventListener('click', () => {
        //     doms.audio.currentTime = item.time;
        // })
        frag.appendChild(lrcEl);
    })
    doms.lyricUl.appendChild(frag);
}

initLrcEl()

/**
 * 容器高度
 */
const containerHeigth = doms.container.clientHeight;
const ulHeight = doms.lyricUl.clientHeight;
const maxOffset = ulHeight - containerHeigth

/**
 * 设置ul的偏移量
 */
function setUlOffset() {
    let index = activeIndex();
    let liHeight = doms.lyricUl.children[0].clientHeight;
    // 歌词居中（li偏移+一半高度 - 容器高度的一半）
    let offset = (liHeight * index + liHeight / 2) - (containerHeigth / 2);
    offset = Math.max(0, offset);
    offset = Math.min(maxOffset, offset);
    doms.lyricUl.style.transform = `translateY(-${offset}px)`
    doms.lyricUl.querySelector('.active')?.classList.remove('active');
    doms.lyricUl.children[index]?.classList.add('active');
}

/**
 * 音频是否正在播放
 * @returns 
 */
function audioIsPlay() {
    return !doms.audio.paused && doms.audio.currentTime > 0 && !doms.audio.ended && doms.audio.readyState > 2;
}


doms.audio.addEventListener('timeupdate', setUlOffset);

/**
 * 点击歌词跳转播放进度
 */
doms.lyricUl.addEventListener('click', function (e) {
    if (e.target.tagName == 'LI') {
        if (!audioIsPlay()) doms.audio.play();
        doms.audio.currentTime = lrcData[e.target.dataset.index].time;
    }
});

/**
 * 扩展：监听键盘事件
 */
document.body.addEventListener('keyup', function (e) {
    if (e.keyCode === 32 || e.code === 'Space') {
        if (audioIsPlay()) doms.audio.pause();
        else doms.audio.play();
    }
    if (e.keyCode === 37 || e.code === 'ArrowLeft') {
        let index = Math.max(0, activeIndex() - 1);
        doms.audio.currentTime = lrcData[index].time;
    }
    if (e.keyCode === 39 || e.code === 'ArrowRight') {
        let index = Math.min(lrcData.length - 1, activeIndex() + 1);
        doms.audio.currentTime = lrcData[index].time;
    }
    if (e.keyCode === 38 || e.code === 'ArrowTop') {
        doms.audio.volume = Math.min(1, doms.audio.volume + 0.1)
    }
    if (e.keyCode === 40 || e.code === 'ArrowDown') {
        doms.audio.volume = Math.max(0, doms.audio.volume - 0.1)
    }
})